﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Silvermoon.Controls
{
    /// <summary>
    /// Panel which determines it's size by the maximum right and bottom location of any control.
    /// The width of the panel is depending on the controls if neither the left nor the right margin is empty. Otherwise the width is layouted by the parent control.
    /// The height of the panel is depending on the controls if neither the top nor the bottom margin is empty. Otherwise the height is layouted by teh parent control.
    /// </summary>
    public class AutoSizePanel : Panel
    {

        private bool IsVerticalFixed { get { return Margin.IsTopEmpty || Margin.IsBottomEmpty; } }
        private bool IsHorizontalFixed { get { return Margin.IsLeftEmpty || Margin.IsRightEmpty; } }

        private Size GetSize()
        {
            int w = 0;
            int h = 0;
            foreach (var c in Controls)
            {
                w = Math.Max(w, c.Right + c.Margin.RightZero);
                h = Math.Max(h, c.Bottom + c.Margin.BottomZero);
            }
            w = IsHorizontalFixed ? w : base.Width;
            h = IsVerticalFixed ? h : base.Height;
            return new Size(w, h);
        }

        protected override void LayoutChildren()
        {
            base.LayoutChildren();
            this.Size = GetSize();
        }

    }
}
